/**
 * Created by wry on 2015/1/13.
 */

var activityService = require('../services/activityService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var questionService = require('../services/questionService');
var moment = require('moment');
var shareService = require('../services/mobile/sharesService');
var md5 = require('MD5');

exports.createActivity = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    var bgNo = req.params.bgNo;
    var objectName = 'activity';
    activityService.createActivityService(input, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when create an activity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when create an activity...!'));
        } else {
            toolUtil.uploadImageService(objectName, result._id, req, function (err, images) {
                var tempImages = new Array();
                var k = 0;
                for (i = 0; i < images.length; i++) {
                    if (images[i] != null) {
                        if (i == bgNo) {
                            tempImages[k++] = {
                                "imageURL": images[i],
                                "isBackgroundImage": true
                            }
                        } else {
                            tempImages[k++] = {
                                "imageURL": images[i]
                            }
                        }
                    }
                }
                activityService.setImagesToActivity(result._id, tempImages, function (err, result) {
                    if (err || tempImages == null) {
                        res.json(messageUtil.composeFailedMessage(req, 'Failed to upload question Images... - ' + err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            })
        }
    })
};

exports.updateActivity = function (req, res) {
    var input = req.body;
    var activityId = req.params.activityId;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('updateActivity - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '更新活动失败'));
        } else {
            var tempImages = [];
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            activityService.updateActivityService(activityId, input, function (err, result) {
                if (err) {
                    logger.error('Failed to updateActivity... - ' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    var data = {};
                    if (input.images != null) {
                        data.images = input.images;
                    }
                    data.deadline = moment(input.deadline).toDate();
                    res.json(messageUtil.composeSucceededMessage(req, null, data));

                    //截至日期放redis
                    if (input.deadline != null) {
                        var deadline = moment(input.deadline).toDate();
                        var key = 'activity:deadline';
                        redisClient.zadd(key, deadline.getTime() / 1000, activityId + '');
                    }
                }
            });
        }
    });
};

/**
 * 获取活动列表
 */
exports.getTopActivityList = function (req, res) {
    var token = req.params.token;
    activityService.getTopActivityListService(token, function (err, results) {
        if (err) {
            logger.error('Failed to get top activity list... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get top activity list... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results[0].concat(results[1])));
        }
    })
};

/**
 * 获取活动详情
 */
exports.getActivityDetail = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    activityService.getActivityDetailService(activityId, token, function (err, result) {
        if (err) {
            logger.error('Failed to get top activity detail... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get top activity detail... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 报名
 */
exports.doRegister = function (req, res) {
    var input = req.body;
    var token = req.params.token;

    activityService.doRegisterService(token, input, function (err, result) {
        if (err) {
            logger.error('Failed to register activity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to register activity... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 发布动态
 */
exports.addActivityInformation = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    var objectName = 'activity';

    toolUtil.uploadImageService(objectName, input.activityId, req, function (err, images) {
        var tempImages = new Array();
        var k = 0;
        for (i = 0; i < images.length; i++) {
            if (images[i] != null) {
                tempImages[k++] = {
                    "photoURL": images[i]
                }
            }
        }
        activityService.addActivityInformationService(tempImages, input, token, function (err, result) {
            if (err) {
                logger.error('Failed to add activity information... - ' + err.message);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to add activity information... - ' + err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            }
        })
    });
};

exports.getActivityPhotoDetail = function (req, res) {
    var activityId = req.params.activityId;
    var imageId = req.params.imageId;

    activityService.getActivityPhotoDetailService(activityId, imageId, function (err, result) {
        if (err) {
            logger.error('Failed to get activity photo detail... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity photo detail... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 评论图片
 */
exports.postPhotoComment = function (req, res) {
    var input = req.body;
    var token = req.params.token;

    activityService.postPhotoCommentService(input, token, function (err, result) {
        if (err) {
            logger.error('Failed to post photo comment... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to post photo comment... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取我的活动
 */
exports.getMyActivity = function (req, res) {
    var token = req.params.token;
    activityService.getMyActivityService(token, function (err, results) {
        if (err) {
            logger.error('Failed to get my activity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get my activity... - ' + err.message));
        } else {
            if (results != null) {
                var temp = new Array();
                results.forEach(function (result) {
                    if (result != null) {
                        result.forEach(function (t) {
                            temp.push(t);
                        })
                    }
                });
                temp.sort(function (a, b) {
                    return b.startDateTime - a.startDateTime;
                });

                //删除重复活动
                var newArray = [];
                var provisionalTable = {};
                for (var i = 0, item; temp[i] != null && (item = temp[i]._id) != null; i++) {
                    if (!provisionalTable[item]) {
                        newArray.push(temp[i]);
                        provisionalTable[item] = true;
                    }
                }
                temp = newArray;

                var weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

                temp.forEach(function (t) {
                    var start = moment(t.startDateTime).format('MM月DD日 HH:mm');
                    var end = moment(t.endDateTime).format('MM月DD日 HH:mm');
                    t._doc['weekDay'] = weekDay[moment(t.startDateTime).format('d')];
                    t._doc['month'] = moment(t.startDateTime).format('YYYY-MM');
                    t._doc['day'] = moment(t.startDateTime).format('D');
                    t._doc['time'] = start + '—' + end;

                    t.startDateTime = undefined;
                    t.endDateTime = undefined;
                })

            }
            res.json(messageUtil.composeSucceededMessage(req, null, temp));
        }
    })
};

/**
 * 获取报名列表
 * @param req
 * @param res
 */
exports.getActivityRegistrationList = function (req, res) {
    var activityId = req.params.activityId;

    activityService.getActivityRegistrationListService(activityId, function (err, results) {
        if (err) {
            logger.error('Failed to get activity registration list ' + err.message)
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity registration list ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取活动聊天室成员
 * @param req
 * @param res
 */
exports.getActivityGroupMember = function (req, res) {
    var groupId = req.params.groupId;

    activityService.getActivityGroupMemberService(groupId, function (err, results) {
        if (err) {
            logger.error('Failed to get activity group member ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity group member ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.searchActivityVenueByKeyword = function (req, res) {
    var keyword = req.params.keyword;

    activityService.searchActivityVenueByKeywordService(keyword, function (err, results) {
        if (err) {
            logger.error('Failed to search activity venue ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to search activity venue' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 上传活动聊天文本信息
 * @param req
 * @param res
 */
exports.postTextMessage = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    activityService.postTextMessageService(token, input, function (err, result) {
        if (err) {
            logger.error('Failed to post activity group chat ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to post activity group chat' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getActivityChats = function (req, res) {
    var groupId = req.params.groupId;

    activityService.getActivityChatsService(groupId, function (err, results) {
        if (err) {
            logger.error('Failed to get activity chats' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity chats' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 创建邻里活动
 */
exports.postNeighbourActivity = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    var input = req.body;
    var token = req.params.token;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('postQuestionNew - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '创建活动失败'));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            if (input.aroundCommunity != null && typeof input.aroundCommunity == 'string') {
                input.aroundCommunity = [input.aroundCommunity];
            }

            activityService.postNeighbourActivityService(token, input, function (err, result) {
                if (err) {
                    logger.error('postQuestionNew - - ' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, '创建活动失败'));
                    toolUtil.deleteImage(images);
                } else {
                    var data = {
                        _id: result[0]._doc._id
                    };
                    toolUtil.hessianInvokeAddScore(token, 3, null, function (score) {
                        if (score != null && score.currentValue != null) {
                            data.currentValue = score.currentValue;
                            data.changeValue = score.changeValue;
                        }
                        if (input.images != null) {
                            data.images = input.images;
                        }
                        data.dateCreated = result[0]._doc.dateCreated;
                        data.deadline = result[0]._doc.deadline;

                        data.shareData = shareService.shareDataService(result[0].title,
                            result[0].desc, result[0].images, 'activity');

                        res.json(messageUtil.composeSucceededMessage(req, null, data));

                        var key = 'catch:q:all:' + result[0].community;
                        redisClient.del(key);
                        redisClient.del('activity_list:' + result[0].community);
                    });


                    //截至日期放redis
                    if (result[0].deadline != null) {
                        var key = 'activity:deadline';
                        redisClient.zadd(key, result[0].deadline.getTime() / 1000, data._id + '');
                    }
                }
            });
        }
    });
};

/**
 *  参加活动
 */
exports.joinInNeighbourActivity = function (req, res) {

    var token = req.params.token;
    var input = req.body;


    activityService.joinInNeighbourActivityService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when joinInNeighbourActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                number: result[3]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};


exports.joinInActivityNew = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    logger.info(input);

    activityService.joinInActivityNewService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when joinInNeighbourActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3001));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result[3], 3001));

            if (result[3].pushFlag) {
                var message = {
                    msgType: 'joinActivity',
                    userId: token,
                    activityId: input.activityId
                };

                toolUtil.putMessageBusinessMQ(message);
            }
        }
    });
};


exports.exitNeighbourActivity = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;

    activityService.exitNeighbourActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when exitNeighbourActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3002));
        } else {
            var data = {
                number: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3002));
        }
    })
};

/**
 * 活动详情
 */
exports.getDetailOfActivity = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    var clickSource = req.cparams.clickSource;
    var vCode = req.cparams.vcode;

    activityService.getDetailOfActivityService(token, activityId, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when getDetailOfQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3003));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3003));

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: activityId,
                    type: 2,
                    clickSource: clickSource,
                    typeDesc: '邻里活动',
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

exports.getActivityPartDetail = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    var clickSource = req.cparams.clickSource;

    activityService.getActivityPartDetailService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityPartDetail ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3003));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3003));

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: activityId,
                    type: 2,
                    clickSource: clickSource,
                    typeDesc: '邻里活动',
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};


/**
 * 活动回复详情
 * @param req
 * @param res
 */
exports.getDetailReplyOfActivity = function (req, res) {
    var page = req.params.page;
    var token = req.params.token;
    var activityId = req.params.activityId;

    var vcode = req.cparams.vcode;

    var key = 'question:reply:list:' + activityId;
    var mark = "";
    if (vcode < 1500) {
        mark = "old";
    } else {
        mark = "new";
    }

    redisClient.HGET(key, mark + ":" + page + ':' + vcode, function (err, value) {
        if (value != null) {
            logger.info('get getDetailReplyOfActivity from catch');
            res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value), 3004))
        } else {
            logger.info('get getDetailReplyOfActivity from mongo');

            activityService.getDetailReplyOfActivityService(token, activityId, page, vcode, function (err, result) {
                if (err) {
                    logger.error('Exception happened when getDetailReplyOfActivity ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 3004));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, result, 3004));
                    redisClient.HSET(key, mark + ":" + page + ':' + vcode, JSON.stringify(result));
                    redisClient.EXPIRE(key, 300);
                }
            })
        }
    });
};


/**
 * 获取活动参与者列表
 * @param req
 * @param res
 */
exports.getActivityPartakeList = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;
    var page = req.params.page;

    activityService.getActivityPartakeListService(token, activityId, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityPartakeList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3005));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3005));
        }
    })
};

exports.getActivityPartakeListNew = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;
    var page = req.params.page;

    activityService.getActivityPartakeListNewService(token, activityId, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityPartakeList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3005));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3005));
        }
    })
};

exports.searchPartake = function (req, res) {
    var activityId = req.body.activityId;
    var keyword = req.body.keyword;

    activityService.searchPartakeService(keyword, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when searchPartake ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3006));
        } else {
            var data = {
                keyword: keyword,
                partake: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3006));
        }
    })
}


exports.deleteActivity = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;

    activityService.deleteActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3007));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 3007));
            toolUtil.hessianInvokeAddScore(token, 14, null, function (score) {

            });
        }
    })
};

/**
 * 活动评论
 * @param req
 * @param res
 */
exports.postActivityReply = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    var activityId = req.params.activityId;

    logger.info(input)

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('postQuestionNew - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '回复失败'));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            activityService.postActivityReplyService(token, activityId, input, function (err, result) {
                if (err) {
                    logger.error('Exception happened when postActivityReply ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    var replyId = {
                        "_id": result[3].replies[result[3].replies.length - 1]._id
                    };
                    replyId.reply = result[3].replies[result[3].replies.length - 1];
                    replyId.replyCountStr = toolUtil.transformNumber(result[3].replies.length);

                    if (replyId.reply.replyTo == null) replyId.reply.replyTo = undefined;

                    if (result[3].createdBy + '' == token) {
                        res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                    } else {
                        toolUtil.hessianInvokeAddScore(token, 4, null, function (score) {
                            if (score != null && score.currentValue != null) {
                                replyId.currentValue = score.currentValue;
                                replyId.changeValue = score.changeValue;
                            }

                            res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                        });

                    }

                    var key = 'catch:q:all:' + result[3].community;

                    redisClient.del(key);
                    redisClient.del('activity_list:' + result[3].community);
                    redisClient.del('question:reply:list:' + activityId);


                    if (input.uList != null && typeof input.uList == 'string') {
                        input.uList = [input.uList];
                    }

                    if (input.replyTo == null && input.replyDesc.indexOf(atFlag) == -1) {
                        toolUtil.putMessageQAMQ({
                            msgType: 'reply2reply',
                            uid: token,
                            questionId: result[3]._id + '',
                            replyDesc: input.replyDesc,
                            contentType: 'activity'
                        });
                    }

                    toolUtil.filteringSensitiveWords(result[3]._id, replyId._id, input.replyDesc, 'activity', function (err, replyDesc) {
                        //推送
                        toolUtil.putMessageQAMQ({
                            msgType: 'reply',
                            isExistAt: input.uList != null && input.uList.length > 0 ? 1 : 0,
                            atUidList: input.uList,
                            replyUid: token,
                            topicId: result[3]._id + '',
                            replyId: replyId._id + '',
                            replyDesc: replyDesc,
                            contentType: 'activity',
                            isAsk: input.replyTo == null ? 0 : 1,
                            toReplyUid: input.replyTo
                        });
                    });

                    //@功能
                    if (input.uList != null && input.uList.length > 0 && input.replyDesc.indexOf(atFlag) != -1) {
                        questionService.replyAtService(result[3], replyId._id, input.uList, 'neighbourActivity', token, input.replyDesc);
                    }
                }
            })
        }
    });
};

exports.thankActivityReply = function (req, res) {
    var activityId = req.params.activityId;
    var replyId = req.params.replyId;
    var replyBy = req.params.replyBy;
    var token = req.params.token;

    activityService.thankActivityReplyService(activityId, replyId, replyBy, token, function (err, result) {
        if (err) {
            logger.error('thankActivityReply--' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3008));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '感谢成功', {replyId: replyId}, 3008));
            redisClient.del('question:reply:list:' + activityId);
        }
    })
}

/**
 * 关闭活动
 * @param req
 * @param res
 */
exports.closeActivity = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;

    activityService.closeActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when closeActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3009));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 3009));

            var key = 'activity:deadline';
            redisClient.ZREM(key, activityId + '');
        }
    })
};

exports.setPartakeStatus = function (req, res) {
    var input = req.body;

    activityService.setPartakeStatusService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setPartakeStatus ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3010));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 3010));
        }
    })
};

exports.setPartakeManagerStatus = function (req, res) {
    var input = req.body;

    activityService.setPartakeManagerStatusService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setPartakeManagerStatus ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3010));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 3010));
        }
    })
};

/**
 * 获取活动列表
 * @param req
 * @param res
 */
exports.getActivityList = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var vCode = req.cparams.vcode;

    if (req.cparams != null) {
        var range = req.cparams.range;
    }

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var key = 'activity_list:' + user.community._id;

            redisClient.HGET(key, ts + ':' + vCode, function (err, value) {
                if (value != null && range == null) {
                    logger.info('get getActivityList from catch');
                    res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value), 3011))
                } else {
                    logger.info('get getActivityList from mongo');
                    activityService.getActivityListService(token, ts, range, vCode, function (err, result) {
                        if (err) {
                            logger.error('Exception happened when getActivityList ...!' + err.message);
                            res.json(messageUtil.composeFailedMessage(req, err.message, 3011));
                        } else {
                            var data = {
                                //ts: result.length > (listPageSize - 1) ? (result[result.length - 1].dateCreated.getTime() - 1000) : (new Date("2000/04/01 00:00:00")).getTime(),
                                ts: Number(ts) + 1,
                                activityList: result
                            };
                            res.json(messageUtil.composeSucceededMessage(req, null, data, 3011));
                            if (range == null) {
                                redisClient.HSET(key, ts + ':' + vCode, JSON.stringify(data));
                                redisClient.EXPIRE(key, 300);
                            }
                        }
                    });
                }
            });
        }
    });
};

/**
 * 举报活动
 */
exports.reportActivity = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    activityService.reportActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the question data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3012));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null, 3012));
        }
    })
};

exports.deleteActivityReply = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    var replyId = req.params.replyId;

    activityService.deleteActivityReplyService(token, activityId, replyId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to deleteActivityReply' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3013));
        } else {
            var data = {
                replyCountStr: result[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3013));
            redisClient.del('question:reply:list:' + activityId);
        }
    })
};

exports.getMyInvolvedActivity = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var vCode = req.cparams.vcode;

    activityService.getMyInvolvedActivityService(token, ts, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityList ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 3014));
        } else {

            var ts = result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime();

            var data = {
                ts: ts,
                activityList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3014));
        }
    })
};

exports.getMyReleasedActivity = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    activityService.getMyReleasedActivityService(token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyReleasedActivityService ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 3015));
        } else {
            var ts = result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime();
            var data = {
                ts: ts,
                activityList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3015));
        }
    })
};

exports.pushActivityMessage = function (req, res) {
    var input = req.body;

    redisClient.get('activityid:' + input.activityId + ':pushcount', function (err, pushCount) {
        pushCount = pushCount ? Number(pushCount) : 0;
        if (pushCount < activityTotalPush) {
            var data = {
                msgContent: input.message,
                activityId: input.activityId
            };
            toolUtil.putMessageActivityMQ(data);
            var result = {
                pushCount: pushCount + 1,
                totalPushCount: activityTotalPush
            };
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3016));
        } else {
            res.json(messageUtil.composeErrorMessage(req, ErrorMessage.ACTIVITY_PUSH, 3016))
        }
    });
};

/**
 * 活动点赞1.6.0
 * @param req
 * @param res
 */
exports.praiseActivity = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;

    activityService.praiseActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying praiseActivity ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 3017));
        } else {
            var data = {
                activityId: activityId,
                praiseCount: result[1],
                isPraise: true
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3017));

            toolUtil.putMessageBusinessMQ({
                msgType: 'praise',
                userId: token,
                contentId: activityId,
                contentType: 'activity'
            })

        }
    })
};

exports.cancelPraiseActivity = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;

    activityService.cancelPraiseActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying praiseActivity ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 3018));
        } else {
            var data = {
                activityId: activityId,
                praiseCount: result[2],
                isPraise: false
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3018));

            //toolUtil.putMessageBusinessMQ({
            //    msgType: 'praise',
            //    userId: token,
            //    contentId: activityId,
            //    contentType: 'activity'
            //})

        }
    });
};

/**
 * 1.6.0他人活动
 * @param req
 * @param res
 */
exports.otherUserActivities = function (req, res) {
    var token = req.params.token;
    var userId = req.params.userId;
    var ts = req.params.ts;
    var vCode = req.cparams.vcode;

    activityService.otherUserActivitiesService(userId, ts, token, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying otherUserActivities ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 3019));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].dateCreated.getTime() : new Date("2000/04/01 00:00:00").getTime(),
                activityList: result
            };

            res.json(messageUtil.composeSucceededMessage(req, null, data, 3019));
        }
    })
};

/**
 * 1.7.0 发布活动
 * @param req
 * @param res
 */
exports.addNewActivity = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");

    var input = req.body;
    var token = req.params.token;
    var oldDesc = input.desc;

    var md5Key = 'app:activity:md5';
    var md5Str = md5(JSON.stringify(req.body));

    redisClient.HGET(md5Key, token, function (err, value) {
        if (value != null && value == md5Str) {
            res.json(messageUtil.composeFailedMessage(req, '重复提交', 3020));
        } else {
            questionService.replaceUgcDescAtService(input.desc, input.uList, function (err, desc) {
                input.desc = desc;


                activityService.addNewActivityService(token, input, function (err, result) {
                    if (err) {
                        logger.error('addNewActivity - - ' + err.message);
                        res.json(messageUtil.composeErrorMessage(req, err, 3020));
                    } else {

                        //发布内容md5
                        redisClient.HSET(md5Key, token, md5(JSON.stringify(req.body)));
                        redisClient.TTL(md5Key, function (err, value) {
                            if (value == -1) {
                                redisClient.EXPIRE(md5Key, toolUtil.getExpireTime());
                            }
                        });


                        var data = {
                            _id: result[0]._doc._id
                        };
                        toolUtil.hessianInvokeAddScore(token, 3, null, function (score) {
                            if (score != null && score.currentValue != null) {
                                data.currentValue = score.currentValue;
                                data.changeValue = score.changeValue;
                            }
                            if (input.images != null) {
                                data.images = input.images;
                            }
                            data.dateCreated = result[0]._doc.dateCreated;
                            data.deadline = result[0]._doc.deadline;

                            data.shareData = shareService.shareDataService(result[0].title,
                                result[0].desc, result[0].images, 'activity');

                            res.json(messageUtil.composeSucceededMessage(req, null, data, 3020));

                            var key = 'catch:q:all:' + result[0].community;
                            redisClient.del(key);
                            redisClient.del('activity_list:' + result[0].community);
                        }, req.query.vcode);


                        //截至日期放redis
                        if (result[0].deadline != null) {
                            var key = 'activity:deadline';
                            redisClient.zadd(key, result[0].deadline.getTime() / 1000, data._id + '');
                        }

                        if (input.key != null) {
                            redisClient.zadd(input.key, result[0].dateCreated.getTime(), JSON.stringify({
                                _id: result[0]._id + '',
                                category: result[0].category
                            }));

                            var arr = input.key.split(':');

                            var message = {
                                msgType: 'iwant',
                                contentId: result[0]._id + '',
                                contentType: 'activity',
                                moudle: arr[2],
                                userId: token,
                                community: result[0].community,
                                isExistAt: oldDesc.indexOf(atFlag) != -1 && input.uList != null && input.uList.length > 0 ? 1 : 0,
                                atUidList: input.uList
                            };
                            if (arr[3] != null) {
                                message.condition = arr[3];
                            }

                            //推送
                            toolUtil.putMessageBusinessMQ(message)

                        } else {
                            //推送
                            toolUtil.putMessageBusinessMQ({
                                msgType: 'concern_qa_push',
                                contentId: result[0]._id + '',
                                contentType: 'activity',
                                isExistAt: oldDesc.indexOf(atFlag) != -1 && input.uList != null && input.uList.length > 0 ? 1 : 0,
                                atUidList: input.uList
                            })
                        }

                    }
                })
            });
        }
    });
};


/**
 * 1.7.0 活动回复
 * @param req
 * @param res
 */
exports.addNewActivityReply = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    var input = req.body;
    var token = req.params.token;
    var activityId = req.params.activityId;

    var md5Key = 'app:reply:md5';
    var md5Str = md5(JSON.stringify(req.body));

    redisClient.HGET(md5Key, token + ':' + activityId, function (err, value) {
        if (value != null && value == md5Str) {
            res.json(messageUtil.composeFailedMessage(req, '重复提交', 3021));
        } else {
            activityService.addNewActivityReplyService(token, activityId, input, function (err, result) {
                if (err) {
                    logger.error('Exception happened when postActivityReply ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 3021));
                } else {

                    //发布内容md5
                    redisClient.HSET(md5Key, token + ':' + activityId, md5(JSON.stringify(req.body)));
                    redisClient.TTL(md5Key, function (err, value) {
                        if (value == -1) {
                            redisClient.EXPIRE(md5Key, 120);
                        }
                    });

                    var replyId = {
                        "_id": result[2].replies[result[2].replies.length - 1]._id
                    };
                    replyId.reply = result[2].replies[result[2].replies.length - 1];
                    replyId.replyCountStr = toolUtil.transformNumber(result[2].replies.length);

                    if (replyId.reply.replyTo == null) replyId.reply.replyTo = undefined;

                    if (result[2].createdBy + '' == token) {
                        res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                    } else {
                        toolUtil.hessianInvokeAddScore(token, 4, null, function (score) {
                            if (score != null && score.currentValue != null) {
                                replyId.currentValue = score.currentValue;
                                replyId.changeValue = score.changeValue;
                            }

                            res.json(messageUtil.composeSucceededMessage(req, null, replyId, 3021));
                        });
                    }

                    //清除缓存
                    var key = 'catch:q:all:' + result[2].community;
                    redisClient.del(key);
                    redisClient.del('activity_list:' + result[2].community);
                    redisClient.del('question:reply:list:' + activityId);

                    //@功能
                    if (input.uList != null && typeof input.uList == 'string') {
                        input.uList = [input.uList];
                    }
                    if (input.uList != null && input.uList.length > 0 && input.replyDesc.indexOf(atFlag) != -1) {
                        questionService.replyAtService(result[2], replyId._id, input.uList, 'neighbourActivity', token, input.replyDesc);
                    }

                    //推送参与回复用户
                    if (input.replyTo == null && input.replyDesc.indexOf(atFlag) == -1) {
                        toolUtil.putMessageQAMQ({
                            msgType: 'reply2reply',
                            uid: token,
                            questionId: result[2]._id + '',
                            replyDesc: input.replyDesc,
                            contentType: 'activity'
                        });
                    }

                    //过滤敏感词
                    toolUtil.filteringSensitiveWords(result[2]._id, replyId._id, input.replyDesc, 'activity', function (err, replyDesc) {
                        //推送
                        toolUtil.putMessageQAMQ({
                            msgType: 'reply',
                            isExistAt: input.uList != null && input.uList.length > 0 ? 1 : 0,
                            atUidList: input.uList,
                            replyUid: token,
                            topicId: result[2]._id + '',
                            replyId: replyId._id + '',
                            replyDesc: replyDesc,
                            contentType: 'activity',
                            isAsk: input.replyTo == null ? 0 : 1,
                            toReplyUid: input.replyTo
                        });
                    });
                }
            })
        }
    });
};

/**
 * 1.7.0 活动更新
 * @param req
 * @param res
 */
exports.updateNewActivity = function (req, res) {
    var input = req.body;
    var activityId = req.params.activityId;

    activityService.updateActivityService(activityId, input, function (err, result) {
        if (err) {
            logger.error('Failed to updateActivity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3022));
        } else {
            var data = {};
            if (input.images != null) {
                data.images = input.images;
            }
            data.deadline = moment(input.deadline).toDate();
            res.json(messageUtil.composeSucceededMessage(req, null, data, 3022));

            //截至日期放redis
            if (input.deadline != null) {
                var deadline = moment(input.deadline).toDate();
                var key = 'activity:deadline';
                redisClient.zadd(key, deadline.getTime() / 1000, activityId + '');
            }
        }
    });

};

exports.getCommunityActivity = function (req, res) {
    var input = req.params;
    var activityId = req.params.activityId;
    var token = req.params.token;

    activityService.getCommunityActivity(token, activityId, input, function (err, result) {
        if (err) {
            logger.error('Failed to getCommunityActivity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3023));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3023));
        }
    });
};

exports.partakeCommunityActivity = function (req, res) {
    var input = req.body;
    var activityId = req.params.activityId;
    var token = req.params.token;

    activityService.partakeCommunityActivity(token, activityId, input, function (err, result) {
        if (err) {
            logger.error('Failed to partakeCommunityActivity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3024));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3024));

            toolUtil.putMessageBusinessMQ({
                msgType: 'join_activity_push',
                userId: token,
                activityId: activityId,
                url: 'http://' + backOfficeHost + '/market/activedetail.html?activityId=' + activityId
            })
        }
    });
};


exports.getElevenInfo = function (req, res) {
    var token = req.params.token;

    activityService.getElevenInfoService(token, function (err, result) {
        if (err) {
            logger.error('Failed to getElevenInfo... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3025));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3025));
        }
    })
};

exports.getCommunityActivityForOutside = function (req, res) {
    var input = req.params;
    var activityId = req.params.activityId;

    activityService.getCommunityActivityForOutside(activityId, input, function (err, result) {
        if (err) {
            logger.error('Failed to getCommunityActivityForOutside... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3026));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3026));
        }
    });
};